﻿<script lang="ts" setup name="storeBudgetConfig">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { auth } from '/@/utils/authFunction';
import { ElMessageBox, ElMessage } from 'element-plus';
import { downloadStreamFile } from '/@/utils/download';
import { useStoreBudgetConfigApi } from '/@/api/store/storeBudgetConfig';
import editDialog from '/@/views/store/storeBudgetConfig/component/editDialog.vue';
import printDialog from '/@/views/system/print/component/hiprint/preview.vue';
import ModifyRecord from '/@/components/table/modifyRecord.vue';
import ImportData from '/@/components/table/importData.vue';

const storeBudgetConfigApi = useStoreBudgetConfigApi();
const printDialogRef = ref();
const editDialogRef = ref();
const importDataRef = ref();
const state = reactive({
	exportLoading: false,
	tableLoading: false,
	refreshLoading: false,
	autoRefresh: true, // 自动刷新开关
	refreshInterval: 30000, // 自动刷新间隔(毫秒)
	stores: {},
	showAdvanceQueryUI: true,
	dropdownData: {} as any,
	selectData: [] as any[],
	tableQueryParams: {} as any,
	tableParams: {
		page: 1,
		pageSize: 20,
		total: 0,
		field: 'createTime', // 默认的排序字段
		order: 'descending', // 排序方向
		descStr: 'descending', // 降序排序的关键字符
	},
	tableData: [],
});

let refreshTimer: NodeJS.Timeout | null = null;

// 页面加载时
onMounted(async () => {
	try {
		// 自动刷新所有预算额度
		await storeBudgetConfigApi.refreshAllBudgets();
	} catch (error) {
		console.warn('自动刷新额度失败:', error);
	}

	const data = (await storeBudgetConfigApi.getDropdownData(true).then((res) => res.data.result)) ?? {};
	state.dropdownData.orgsId = data.orgsId;
	
	// 启动自动刷新
	startAutoRefresh();
});

// 页面卸载时清理定时器
onUnmounted(() => {
	if (refreshTimer) {
		clearInterval(refreshTimer);
		refreshTimer = null;
	}
});

// 启动自动刷新
const startAutoRefresh = () => {
	if (state.autoRefresh && !refreshTimer) {
		refreshTimer = setInterval(async () => {
			if (!state.tableLoading && !state.refreshLoading) {
				try {
					await storeBudgetConfigApi.refreshAllBudgets();
					await handleQuery();
				} catch (error) {
					console.warn('自动刷新失败:', error);
				}
			}
		}, state.refreshInterval);
	}
};

// 停止自动刷新
const stopAutoRefresh = () => {
	if (refreshTimer) {
		clearInterval(refreshTimer);
		refreshTimer = null;
	}
};

// 切换自动刷新
const toggleAutoRefresh = () => {
	state.autoRefresh = !state.autoRefresh;
	if (state.autoRefresh) {
		startAutoRefresh();
		ElMessage.success('已开启自动刷新');
	} else {
		stopAutoRefresh();
		ElMessage.info('已关闭自动刷新');
	}
};

// 查询操作
const handleQuery = async (params: any = {}) => {
	state.tableLoading = true;
	state.tableParams = Object.assign(state.tableParams, params);
	const result = await storeBudgetConfigApi.page(Object.assign(state.tableQueryParams, state.tableParams)).then((res) => res.data.result);
	state.tableParams.total = result?.total;
	state.tableData = result?.items ?? [];
	state.tableLoading = false;
};

// 列排序
const sortChange = async (column: any) => {
	state.tableParams.field = column.prop;
	state.tableParams.order = column.order;
	await handleQuery();
};

// 删除
const delStoreBudgetConfig = (row: any) => {
	ElMessageBox.confirm(`确定要删除吗?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await storeBudgetConfigApi.delete({ id: row.id });
			handleQuery();
			ElMessage.success('删除成功');
		})
		.catch(() => {});
};

// 批量删除
const batchDelStoreBudgetConfig = () => {
	ElMessageBox.confirm(`确定要删除${state.selectData.length}条记录吗?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await storeBudgetConfigApi.batchDelete(state.selectData.map((u) => ({ id: u.id }))).then((res) => {
				ElMessage.success(`成功批量删除${res.data.result}条记录`);
				handleQuery();
			});
		})
		.catch(() => {});
};

// 刷新单个预算
const refreshBudget = async (row: any) => {
	try {
		state.refreshLoading = true;
		await storeBudgetConfigApi.refreshBudget(row.id);
		ElMessage.success('刷新成功');
		await handleQuery();
	} catch (error) {
		ElMessage.error('刷新失败');
	} finally {
		state.refreshLoading = false;
	}
};

// 刷新所有预算
const refreshAllBudgets = async () => {
	ElMessageBox.confirm('确定要刷新所有预算数据吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			try {
				state.refreshLoading = true;
				await storeBudgetConfigApi.refreshAllBudgets();
				ElMessage.success('刷新成功');
				await handleQuery();
			} catch (error) {
				ElMessage.error('刷新失败');
			} finally {
				state.refreshLoading = false;
			}
		})
		.catch(() => {});
};

// 计算使用率
const getUsageRate = (row: any) => {
	if (!row.totalAmount || row.totalAmount === 0) return '0%';
	const totalUsed = (row.usedAmount || 0) + (row.pendingAmount || 0);
	const rate = ((totalUsed / row.totalAmount) * 100).toFixed(1);
	return `${rate}%`;
};

// 判断是否为当前有效预算
const isCurrentActive = (row: any) => {
	const now = new Date();
	const startDate = new Date(row.startDate);
	const endDate = new Date(row.endDate);
	return startDate <= now && endDate >= now;
};

// 获取使用率颜色
const getUsageRateType = (row: any) => {
	if (!row.totalAmount || row.totalAmount === 0) return '';
	const totalUsed = (row.usedAmount || 0) + (row.pendingAmount || 0);
	const rate = (totalUsed / row.totalAmount) * 100;

	if (rate >= (row.warningThreshold || 80)) return 'danger';
	if (rate >= 60) return 'warning';
	return 'success';
};

// 获取行的CSS类名
const getRowClassName = ({ row }: { row: any }) => {
	if (!row.isWarningEnabled) return 'normal-row';
	
	const usageRateType = getUsageRateType(row);
	return `${usageRateType}-row`;
};

// 导出数据
const exportStoreBudgetConfigCommand = async (command: string) => {
	try {
		state.exportLoading = true;
		if (command === 'select') {
			const params = Object.assign({}, state.tableQueryParams, state.tableParams, { selectKeyList: state.selectData.map((u) => u.id) });
			await storeBudgetConfigApi.exportData(params).then((res) => downloadStreamFile(res));
		} else if (command === 'current') {
			const params = Object.assign({}, state.tableQueryParams, state.tableParams);
			await storeBudgetConfigApi.exportData(params).then((res) => downloadStreamFile(res));
		} else if (command === 'all') {
			const params = Object.assign({}, state.tableQueryParams, state.tableParams, { page: 1, pageSize: 99999999 });
			await storeBudgetConfigApi.exportData(params).then((res) => downloadStreamFile(res));
		}
	} finally {
		state.exportLoading = false;
	}
};

handleQuery();
</script>
<template>
	<div class="storeBudgetConfig-container" v-loading="state.exportLoading">
		<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
			<el-form :model="state.tableQueryParams" ref="queryForm" labelWidth="90">
				<el-row>
					<el-col :xs="24" :sm="4" :md="4" :lg="4" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="区域ID">
							<el-select clearable filterable v-model="state.tableQueryParams.orgsId" placeholder="请选择区域ID">
								<el-option v-for="(item, index) in state.dropdownData.orgsId ?? []" :key="index" :value="item.value" :label="item.label" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="4" :md="4" :lg="4" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="预算名称">
							<el-input clearable v-model="state.tableQueryParams.budgetName" placeholder="请输入预算名称" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
						<el-form-item>
							<el-button-group style="display: flex; align-items: center">
								<el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'storeBudgetConfig:page'" v-reclick="1000"> 查询 </el-button>
								<el-button icon="ele-Refresh" @click="() => (state.tableQueryParams = {})"> 重置 </el-button>
								<el-button type="success" icon="ele-Refresh" @click="refreshAllBudgets" :loading="state.refreshLoading" style="margin-left: 5px"> 刷新额度 </el-button>
								<el-button :type="state.autoRefresh ? 'warning' : 'info'" icon="ele-Timer" @click="toggleAutoRefresh" style="margin-left: 5px"> 
									{{ state.autoRefresh ? '关闭自动刷新' : '开启自动刷新' }} 
								</el-button>
								<el-button
									type="danger"
									style="margin-left: 5px"
									icon="ele-Delete"
									@click="batchDelStoreBudgetConfig"
									:disabled="state.selectData.length == 0"
									v-auth="'storeBudgetConfig:batchDelete'"
								>
									删除
								</el-button>
								<el-button type="primary" style="margin-left: 5px" icon="ele-Plus" @click="editDialogRef.openDialog(null, '新增区域预算配置表')" v-auth="'storeBudgetConfig:add'"> 新增 </el-button>
								<el-dropdown :show-timeout="70" :hide-timeout="50" @command="exportStoreBudgetConfigCommand">
									<el-button type="primary" style="margin-left: 5px" icon="ele-FolderOpened" v-reclick="20000" v-auth="'storeBudgetConfig:export'"> 导出 </el-button>
									<template #dropdown>
										<el-dropdown-menu>
											<el-dropdown-item command="select" :disabled="state.selectData.length == 0">导出选中</el-dropdown-item>
											<el-dropdown-item command="current">导出本页</el-dropdown-item>
											<el-dropdown-item command="all">导出全部</el-dropdown-item>
										</el-dropdown-menu>
									</template>
								</el-dropdown>
								<el-button type="warning" style="margin-left: 5px" icon="ele-MostlyCloudy" @click="importDataRef.openDialog()" v-auth="'storeBudgetConfig:import'"> 导入 </el-button>
							</el-button-group>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
		<el-card class="full-table" shadow="hover" style="margin-top: 5px">
			<el-table
				:data="state.tableData"
				@selection-change="
					(val: any[]) => {
						state.selectData = val;
					}
				"
				style="width: 100%"
				v-loading="state.tableLoading"
				tooltip-effect="light"
				row-key="id"
				@sort-change="sortChange"
				:row-class-name="getRowClassName"
				border
			>
				<el-table-column type="selection" width="40" align="center" v-if="auth('storeBudgetConfig:batchDelete') || auth('storeBudgetConfig:export')" />
				<el-table-column type="index" label="序号" width="55" align="center" />
				<el-table-column prop="orgsId" label="区域ID" :formatter="(row: any) => row.orgsFkDisplayName" show-overflow-tooltip />
				<el-table-column prop="budgetName" label="预算名称" show-overflow-tooltip />
				<el-table-column label="状态" align="center" width="80">
					<template #default="scope">
						<el-tag v-if="isCurrentActive(scope.row)" type="success" size="small">当前</el-tag>
						<el-tag v-else type="info" size="small">历史</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="startDate" label="开始时间" show-overflow-tooltip width="100">
					<template #default="scope">
						{{ new Date(scope.row.startDate).toLocaleDateString('zh-CN') }}
					</template>
				</el-table-column>
				<el-table-column prop="endDate" label="结束时间" show-overflow-tooltip width="100">
					<template #default="scope">
						{{ new Date(scope.row.endDate).toLocaleDateString('zh-CN') }}
					</template>
				</el-table-column>
				<el-table-column prop="totalAmount" label="总额度" show-overflow-tooltip align="right">
					<template #default="scope">
						{{ scope.row.totalAmount?.toLocaleString() }}
					</template>
				</el-table-column>
				<el-table-column prop="usedAmount" label="已使用" show-overflow-tooltip align="right">
					<template #default="scope">
						{{ (scope.row.usedAmount || 0).toLocaleString() }}
					</template>
				</el-table-column>
				<el-table-column prop="pendingAmount" label="申请中" show-overflow-tooltip align="right">
					<template #default="scope">
						{{ (scope.row.pendingAmount || 0).toLocaleString() }}
					</template>
				</el-table-column>
				<el-table-column label="使用情况" show-overflow-tooltip align="center" width="200">
					<template #default="scope">
						<div class="usage-info">
							<div class="usage-rate">
								<el-tag :type="getUsageRateType(scope.row)" size="small">
									{{ getUsageRate(scope.row) }}
								</el-tag>
							</div>
							<div class="usage-progress">
								<el-progress 
									:percentage="parseFloat(getUsageRate(scope.row))" 
									:status="getUsageRateType(scope.row) === 'danger' ? 'exception' : (getUsageRateType(scope.row) === 'warning' ? 'warning' : 'success')"
									:stroke-width="8"
									:show-text="false"
								/>
							</div>
							<div class="usage-detail" style="font-size: 12px; color: #666;">
								已用: {{ (scope.row.usedAmount || 0).toLocaleString() }} | 申请中: {{ (scope.row.pendingAmount || 0).toLocaleString() }}
							</div>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="warningThreshold" label="预警阈值" show-overflow-tooltip align="center">
					<template #default="scope"> {{ scope.row.warningThreshold }}% </template>
				</el-table-column>
				<el-table-column prop="isWarningEnabled" label="启用预警" show-overflow-tooltip align="center">
					<template #default="scope">
						<el-tag v-if="scope.row.isWarningEnabled" type="success"> 是 </el-tag>
						<el-tag type="info" v-else> 否 </el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="remark" label="备注" show-overflow-tooltip />
				<el-table-column label="修改记录" width="100" align="center" show-overflow-tooltip>
					<template #default="scope">
						<ModifyRecord :data="scope.row" />
					</template>
				</el-table-column>
				<el-table-column label="操作" width="180" align="center" fixed="right" show-overflow-tooltip v-if="auth('storeBudgetConfig:update') || auth('storeBudgetConfig:delete')">
					<template #default="scope">
						<el-button icon="ele-Refresh" size="small" text type="success" @click="refreshBudget(scope.row)" :loading="state.refreshLoading"> 刷新 </el-button>
						<el-button icon="ele-Edit" size="small" text type="primary" @click="editDialogRef.openDialog(scope.row, '编辑区域预算配置表')" v-auth="'storeBudgetConfig:update'"> 编辑 </el-button>
						<el-button icon="ele-Delete" size="small" text type="primary" @click="delStoreBudgetConfig(scope.row)" v-auth="'storeBudgetConfig:delete'"> 删除 </el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				v-model:currentPage="state.tableParams.page"
				v-model:page-size="state.tableParams.pageSize"
				@size-change="(val: any) => handleQuery({ pageSize: val })"
				@current-change="(val: any) => handleQuery({ page: val })"
				layout="total, sizes, prev, pager, next, jumper"
				:page-sizes="[10, 20, 50, 100, 200, 500]"
				:total="state.tableParams.total"
				size="small"
				background
			/>
			<ImportData ref="importDataRef" :import="storeBudgetConfigApi.importData" :download="storeBudgetConfigApi.downloadTemplate" v-auth="'storeBudgetConfig:import'" @refresh="handleQuery" />
			<printDialog ref="printDialogRef" :title="'打印区域预算配置表'" @reloadTable="handleQuery" />
			<editDialog ref="editDialogRef" @reloadTable="handleQuery" />
		</el-card>
	</div>
</template>
<style scoped>
:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}

.usage-info {
	padding: 8px;
}

.usage-rate {
	margin-bottom: 6px;
}

.usage-progress {
	margin-bottom: 4px;
}

.usage-detail {
	text-align: center;
	white-space: nowrap;
	font-size: 11px !important;
}

/* 表格行根据状态变色 */
:deep(.el-table tbody tr.danger-row) {
	background-color: #fef0f0;
}

:deep(.el-table tbody tr.warning-row) {
	background-color: #fdf6ec;
}

:deep(.el-table tbody tr.normal-row) {
	background-color: #f0f9ff;
}
</style>
